package com.wqr.mobile.android.ui.net;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.wqr.mobile.android.ui.api.API;

/**
 * 
 * @author wenqiurong
 * 
 */
public class MyImagedownloader implements API {
	private HashMap<String, SoftReference<Bitmap>> imageCache;
	private Context mContext;
	private NetworkManager mNetworkManager;

	// 专辑列表调用
	public MyImagedownloader(Context context) {
		this.mContext = context;
		imageCache = new HashMap<String, SoftReference<Bitmap>>();
		mNetworkManager = NetworkManager.getInstance();
	}

	public void loadBitmap(final String imageUrl, final ImageView icon, final Handler h) {
		if (h != null) {
			h.sendEmptyMessage(START);
		}

		Bitmap bitmap = null;
		// 判断缓存中是否有对资源数据 的引用
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
			bitmap = softReference.get();
			if (bitmap != null) {
				icon.setImageBitmap(bitmap);
			}
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				new ImageCallback() {
					@Override
					public void imageLoaded(Bitmap imageDrawable, String imageUrl, ImageView icon) {
						// int width = imageDrawable.getWidth();
						// int height = imageDrawable.getHeight();
						// if (width > height) {
						// Matrix matrix = new Matrix();
						// matrix.postRotate(90); /* 翻转90度 */
						// imageDrawable = Bitmap.createBitmap(imageDrawable, 0, 0, width, height, matrix, true);
						// }
						icon.setImageBitmap(imageDrawable);
					}
				}.imageLoaded((Bitmap) message.obj, imageUrl, icon);
			}
		};
		// 下载数据，同时建立对资源的引用
		new Thread() {
			@Override
			public void run() {
				Bitmap bitmap = mNetworkManager.downloadImages(mContext, imageUrl);
				imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));
				Message message = handler.obtainMessage(0, bitmap);
				handler.sendMessage(message);
				if (h != null) {
					h.sendEmptyMessage(FINISHED);
				}
			}
		}.start();
	}

	public void clearCache() {
		imageCache.clear();
	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap imageDrawable, String imageUrl, ImageView icon);
	}
}
